const express = require('express')
const bodyParser = require('body-parser')
const methodOverride = require('method-override')
const mongoose = require('mongoose')
const session = require("express-session");
const  jwt = require('jsonwebtoken');
const app = express()

var morgan = require('morgan');
var expressJwt = require('express-jwt');
app.use(morgan('short'));
const request  = require("request")
const router = express.Router()
var crypto = require("crypto");
app.use(bodyParser.json())
app.use(methodOverride())
//
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin",req.headers.origin);
    
 res.header('Access-Control-Allow-Credentials', true) 

     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();
}); 
mongoose.connect('mongodb://admin:123@10.30.252.76:8080,10.30.252.76:8181/performance?replicaSet=rs0', { useNewUrlParser: true },err=>{
  console.log(err);
})
app.use(session({
  secret: 'recommand 128 bytes random string', // 建议使用 128 个字符的随机字符串
  cookie: { maxAge: 60 * 1000 }
}));
app.use(express.static(__dirname+'/public'));
app.use(express.static(__dirname+'/public/dist'));

app.use(function (err, req, res, next) {
    if (err.name === 'UnauthorizedError') {
      res.status(401).send('invalid token');
    }
  });
// app.use(expressJwt({
//     secret: "197925"//加密密钥，可换
// }).unless({
//     path: ["/mobileJixiao/","/mobile_jixiao/"]//添加不需要token的接口
//  }));
 app.get('/mobileJixiao',function(req,res,next){
  var s = `http://wbapp.gdit.edu.cn:8080/mobileapi_ydxy/open/lapp/verify?accessToken=${req.query.accessToken}&uniqueCode=${req.query.uniqueCode}&yyid=${req.query.yyid}`
  request(s, async function (error, response, body) {
     if (!error &&  response.statusCode == 200) {
          var ss =JSON.parse(body);
          if(ss.code ==="0")
          {
              let key = 'hZxcLWDPI0PIZ8lWQXtQCA==';
              var cipherChunks = [];
              var decipher = crypto.createDecipheriv('aes-128-ecb', Buffer.from(key, 'base64'), '');
              decipher.setAutoPadding(true);
              cipherChunks.push(decipher.update(ss.data, 'base64', 'utf8'));
              cipherChunks.push(decipher.final('utf8'));
              var person = JSON.parse( cipherChunks.join(''));
              const Teacher = mongoose.model('Teacher');  
              console.log("user number "+person.userId)
              var teacher = await Teacher.findOne({number:person.userId}).exec();
              console.log("teacher "+teacher)
              if(teacher)
              {
                  const token = jwt.sign({
                      number: teacher.hrNumber,
                      _id: teacher._id
                  }, '197925', { expiresIn: '2h' });
                  res.redirect(`http://xssw.gdit.edu.cn/mobile_jixiao/index.html?number=${person.userId}&token=${token}`);
     
              }else{
                  res.status(500).send("系统无该老师账号");
              }
          }else{
            res.status(500).send(error)
          }
      }else{
          res.status(500).send(error)
      }
  });
}) 
app.use('/',require('./model'))
app.use('/',require('./router/teacher.js'))
app.use('/',require('./router/transaction.js'))
app.use('/',require('./router/performance.js'))
app.use('/',require('./router/voter.js'))
app.use('/',require('./router/shujiVoter.js'))
app.use('/',require('./router/good.js'))


app.listen(4444, () => {
  console.log('Express server listening on port 3000')
})


